package com.scs.application.modules.base.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.Mfg;
import com.scs.application.modules.base.service.MatrService;
import com.scs.application.modules.base.service.MfgService;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/mfg")
public class MfgController extends CrudController<MfgService, Mfg>{
    @Autowired
    MatrService matrService;
    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Mfg entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功",  entity);
    }


    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        int matrsCount = matrService.count(Wrappers.<Matr>query().in("mfg_id", ids));
        if (matrsCount > 0) {
            throw new BusinessException("对不起，您所选择的厂商下面有关联耗材，暂时不能删除");
        }
        Boolean isOk = service.removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }
}
